"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { motion } from "framer-motion"
import { 
  Calendar, 
  Users, 
  Trophy, 
  Clock, 
  MapPin, 
  ExternalLink, 
  Share2, 
  Heart, 
  BookOpen,
  Star,
  Award,
  Target,
  ChevronLeft,
  Eye
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { competitionsApi, Competition } from "@/lib/api"
import { useAuth } from "@/contexts/auth-context"
import { LoadingScreen } from "@/components/loading-screen"
import { useToast } from "@/hooks/use-toast"

export default function CompetitionDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { user, isAuthenticated } = useAuth()
  const { toast } = useToast()
  const [competition, setCompetition] = useState<Competition | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isJoined, setIsJoined] = useState(false)
  const [isFavorited, setIsFavorited] = useState(false)

  useEffect(() => {
    const fetchCompetition = async () => {
      try {
        setIsLoading(true)
        const response = await competitionsApi.getCompetition(params.id as string)
        setCompetition(response || null)
      } catch (error) {
        console.error("Failed to fetch competition:", error)
        router.push("/")
      } finally {
        setIsLoading(false)
      }
    }

    if (params.id) {
      fetchCompetition()
    }
  }, [params.id, router])

  const handleJoinCompetition = async () => {
    if (!isAuthenticated) {
      toast({
        title: "⚠️ 需要登录",
        description: "请先登录后再参加竞赛",
        variant: "destructive"
      })
      // 保存当前页面路径
      const currentPath = window.location.pathname + window.location.search
      localStorage.setItem('redirectAfterLogin', currentPath)
      router.push("/auth/login")
      return
    }
    
    try {
      // TODO: 实现加入竞赛的API调用
      setIsJoined(true)
      toast({
        title: "🎉 参赛成功！",
        description: "欢迎加入竞赛，祝你取得好成绩！"
      })
    } catch (error) {
      console.error("Failed to join competition:", error)
      toast({
        title: "❌ 参赛失败",
        description: "加入竞赛时出现错误，请稍后重试",
        variant: "destructive"
      })
    }
  }

  const handleToggleFavorite = async () => {
    if (!isAuthenticated) {
      toast({
        title: "⚠️ 需要登录",
        description: "请先登录后再收藏竞赛",
        variant: "destructive"
      })
      // 保存当前页面路径
      const currentPath = window.location.pathname + window.location.search
      localStorage.setItem('redirectAfterLogin', currentPath)
      router.push("/auth/login")
      return
    }
    
    try {
      // TODO: 实现收藏/取消收藏的API调用
      const newFavoriteState = !isFavorited
      setIsFavorited(newFavoriteState)
      toast({
        title: newFavoriteState ? "⭐ 收藏成功" : "💔 取消收藏",
        description: newFavoriteState ? "已添加到我的收藏" : "已从收藏中移除"
      })
    } catch (error) {
      console.error("Failed to toggle favorite:", error)
      toast({
        title: "❌ 操作失败",
        description: "收藏操作失败，请稍后重试",
        variant: "destructive"
      })
    }
  }

  const handleShare = async () => {
    try {
      await navigator.share({
        title: competition?.title,
        text: competition?.description,
        url: window.location.href,
      })
    } catch (error) {
      // 如果不支持原生分享，复制链接到剪贴板
      navigator.clipboard.writeText(window.location.href)
    }
  }

  if (isLoading) {
    return <LoadingScreen />
  }

  if (!competition) {
    return (
      <div className="min-h-screen pt-20 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-white mb-4">竞赛不存在</h1>
          <Button onClick={() => router.push("/")} variant="outline">
            返回首页
          </Button>
        </div>
      </div>
    )
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "long",
      day: "numeric",
    })
  }

  const getDaysRemaining = (deadline: string) => {
    const now = new Date()
    const end = new Date(deadline)
    const diffTime = end.getTime() - now.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  }

  const daysRemaining = getDaysRemaining(competition.end_date)

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 返回按钮 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          className="mb-6"
        >
          <Button
            variant="ghost"
            onClick={() => router.back()}
            className="text-white hover:text-blue-300"
          >
            <ChevronLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 主要内容 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 竞赛头部信息 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="space-y-4"
            >
              <div className="flex flex-wrap gap-2 mb-4">
                {competition.tags?.map((tag) => (
                  <Badge key={tag} variant="secondary" className="bg-blue-500/20 text-blue-300">
                    {tag}
                  </Badge>
                ))}
                <Badge 
                  variant="outline" 
                  className={`${
                    competition.difficulty === "Beginner" 
                      ? "border-green-500 text-green-400" 
                      : competition.difficulty === "Intermediate"
                      ? "border-yellow-500 text-yellow-400"
                      : "border-red-500 text-red-400"
                  }`}
                >
                  {competition.difficulty}
                </Badge>
              </div>

              <h1 className="text-4xl font-bold text-white mb-4">
                {competition.title}
              </h1>

              <div className="flex items-center gap-6 text-gray-300">
                <div className="flex items-center gap-2">
                  <Users className="w-5 h-5" />
                  <span>{competition.participants_count || 0} 参与者</span>
                </div>
                <div className="flex items-center gap-2">
                  <Eye className="w-5 h-5" />
                  <span>{competition.views || 0} 浏览</span>
                </div>
                <div className="flex items-center gap-2">
                  <Calendar className="w-5 h-5" />
                  <span>截止: {formatDate(competition.end_date)}</span>
                </div>
              </div>

              <p className="text-gray-300 text-lg leading-relaxed">
                {competition.description}
              </p>
            </motion.div>

            {/* 竞赛详情标签页 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Tabs defaultValue="overview" className="w-full">
                <TabsList className="grid w-full grid-cols-4 bg-gray-800/50">
                  <TabsTrigger value="overview" className="text-white">概览</TabsTrigger>
                  <TabsTrigger value="rules" className="text-white">规则</TabsTrigger>
                  <TabsTrigger value="timeline" className="text-white">时间线</TabsTrigger>
                  <TabsTrigger value="resources" className="text-white">资源</TabsTrigger>
                </TabsList>

                <TabsContent value="overview" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">竞赛概览</CardTitle>
                    </CardHeader>
                    <CardContent className="text-gray-300 space-y-4">
                      <div>
                        <h4 className="font-semibold text-white mb-2">竞赛目标</h4>
                        <p>{competition.description}</p>
                      </div>
                      <div>
                        <h4 className="font-semibold text-white mb-2">评估标准</h4>
                        <p>根据解决方案的创新性、技术实现和实际应用价值进行评估。</p>
                      </div>
                      <div>
                        <h4 className="font-semibold text-white mb-2">提交要求</h4>
                        <ul className="list-disc list-inside space-y-1">
                          <li>完整的项目代码</li>
                          <li>详细的技术文档</li>
                          <li>演示视频或在线演示</li>
                        </ul>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="rules" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">竞赛规则</CardTitle>
                    </CardHeader>
                    <CardContent className="text-gray-300 space-y-4">
                      <div>
                        <h4 className="font-semibold text-white mb-2">参赛资格</h4>
                        <ul className="list-disc list-inside space-y-1">
                          <li>个人或团队均可参赛（团队最多5人）</li>
                          <li>所有参赛者必须注册并同意竞赛条款</li>
                          <li>每个参赛者只能参与一个团队</li>
                        </ul>
                      </div>
                      <div>
                        <h4 className="font-semibold text-white mb-2">提交规则</h4>
                        <ul className="list-disc list-inside space-y-1">
                          <li>必须在截止时间前提交</li>
                          <li>代码必须是原创或正确引用</li>
                          <li>禁止抄袭或使用他人作品</li>
                        </ul>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="timeline" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">竞赛时间线</CardTitle>
                    </CardHeader>
                    <CardContent className="text-gray-300">
                      <div className="space-y-4">
                        <div className="flex items-center gap-4">
                          <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                          <div>
                            <p className="font-semibold text-white">竞赛开始</p>
                            <p className="text-sm">{formatDate(competition.start_date)}</p>
                          </div>
                        </div>
                        {competition.submission_deadline && (
                          <div className="flex items-center gap-4">
                            <div className="w-3 h-3 bg-orange-500 rounded-full"></div>
                            <div>
                              <p className="font-semibold text-white">提交截止</p>
                              <p className="text-sm">{formatDate(competition.submission_deadline)}</p>
                            </div>
                          </div>
                        )}
                        <div className="flex items-center gap-4">
                          <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                          <div>
                            <p className="font-semibold text-white">竞赛结束</p>
                            <p className="text-sm">{formatDate(competition.end_date)}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-4">
                          <div className="w-3 h-3 bg-purple-500 rounded-full"></div>
                          <div>
                            <p className="font-semibold text-white">结果公布</p>
                            <p className="text-sm">竞赛结束后一周内</p>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="resources" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">相关资源</CardTitle>
                    </CardHeader>
                    <CardContent className="text-gray-300 space-y-4">
                      <div>
                        <h4 className="font-semibold text-white mb-2">数据集</h4>
                        <p>竞赛相关的数据集将在竞赛开始后提供下载链接。</p>
                      </div>
                      <div>
                        <h4 className="font-semibold text-white mb-2">技术文档</h4>
                        <p>详细的API文档和技术指南可在竞赛平台上查看。</p>
                      </div>
                      <div>
                        <h4 className="font-semibold text-white mb-2">社区支持</h4>
                        <p>加入竞赛讨论群，与其他参赛者交流经验。</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>
              </Tabs>
            </motion.div>
          </div>

          {/* 侧边栏 */}
          <div className="space-y-6">
            {/* 竞赛状态卡片 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.3 }}
            >
              <Card className="bg-gray-800/50 border-gray-700">
                <CardHeader>
                  <CardTitle className="text-white flex items-center gap-2">
                    <Trophy className="w-5 h-5 text-yellow-400" />
                    竞赛信息
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">奖金池</span>
                    <span className="text-xl font-bold text-green-400">{competition.prize}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">剩余时间</span>
                    <span className={`font-bold ${daysRemaining <= 7 ? "text-red-400" : "text-blue-400"}`}>
                      {daysRemaining > 0 ? `${daysRemaining} 天` : "已结束"}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">参与人数</span>
                    <span className="text-white">{competition.participants_count || 0}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">主办方</span>
                    <span className="text-white">{competition.platform}</span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* 操作按钮 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
              className="space-y-3"
            >
              <Button
                onClick={handleJoinCompetition}
                className="w-full bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                disabled={isJoined || daysRemaining <= 0}
              >
                {isJoined ? "已参加" : daysRemaining <= 0 ? "竞赛已结束" : "参加竞赛"}
              </Button>
              
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleToggleFavorite}
                  className="flex-1 border-gray-600 text-white hover:bg-gray-700"
                >
                  <Heart className={`w-4 h-4 mr-2 ${isFavorited ? "fill-red-500 text-red-500" : ""}`} />
                  {isFavorited ? "已收藏" : "收藏"}
                </Button>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleShare}
                  className="flex-1 border-gray-600 text-white hover:bg-gray-700"
                >
                  <Share2 className="w-4 h-4 mr-2" />
                  分享
                </Button>
              </div>

              {competition.external_url && (
                <Button
                  variant="outline"
                  className="w-full border-gray-600 text-white hover:bg-gray-700"
                  onClick={() => window.open(competition.external_url, "_blank")}
                >
                  <ExternalLink className="w-4 h-4 mr-2" />
                  访问官方页面
                </Button>
              )}
            </motion.div>

            {/* 相关竞赛 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.5 }}
            >
              <Card className="bg-gray-800/50 border-gray-700">
                <CardHeader>
                  <CardTitle className="text-white flex items-center gap-2">
                    <Star className="w-5 h-5 text-yellow-400" />
                    相关竞赛
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-gray-400 text-sm">暂无相关竞赛推荐</p>
                </CardContent>
              </Card>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}